package com.keydom.ropeskipping.service;

import android.util.Log;

import com.google.gson.Gson;
import com.keydom.ropeskipping.dot.CardHomeworkResultDTO;
import com.keydom.ropeskipping.dot.SkipDataDTO;
import com.keydom.ropeskipping.dot.StudentHomeworkDTO;
import com.keydom.ropeskipping.utils.AESEncryption;
import com.keydom.ropeskipping.utils.HttpConnResponse;
import com.keydom.ropeskipping.utils.HttpRequestUtil;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;

import org.json.JSONArray;
import org.json.JSONObject;

/**
 * @author ch
 * @date 2024年05月13日 11:13
 */
public class SkipWorkServiceImpl {

    private static final String SPORTS_WORK_PATCH = "/sports/v1/student/card/tm/query/hw";

//    private static final String BASE_URL = "https://aipe.cmiivip.com";
    private static final String BASE_URL = "https://sports.unissense.top";

    public static final String APP_ID = "bcdb7947b36f4c4883ba7f20fbddd35c";

    /**
     * @param homeworkRedirectUrl 运动结果回调地址
     */
    public static void upSkipHomework(String homeworkRedirectUrl, SkipDataDTO skipDataDTO) {
        Map<String, Object> params = new HashMap<>();
        params.put("sportNum", skipDataDTO.getSportNum());
        params.put("sportTime", skipDataDTO.getSportTime());
        params.put("beginTime", skipDataDTO.getBeginTime());
        params.put("completeTime", skipDataDTO.getCompleteTime());
        try {
            HttpConnResponse res = requestCommon(params, homeworkRedirectUrl);
            if (res.getCode() == 200) {
            }
        } catch (Exception e) {
        }
    }

    /**
     * @param historyRedirectUrl 历史数据回传地址
     * @param dataDTOList        自由跳数据
     */
    public static void upHistorySkip(String historyRedirectUrl, List<SkipDataDTO> dataDTOList) {
        try {
            Map<String, String> headers = getHeaders();
            JSONObject requestJson = new JSONObject();
            requestJson.put("encryptJson", AESEncryption.encrypt(new Gson().toJson(dataDTOList)));
            String json = requestJson.toString();
            HttpConnResponse res = HttpRequestUtil.sendPostRequest(historyRedirectUrl, requestJson.toString(), headers);
            JSONObject resultJson = new JSONObject(res.getBody());
            Log.e("TAG", "upHistorySkipBody: " + res.getBody());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询 作业
     * @param imei 设备号
     * @return
     */
    public static CardHomeworkResultDTO querySkipHomeworkById(String imei) {
        String url = BASE_URL + SPORTS_WORK_PATCH;
        Map<String, Object> params = new HashMap<>();
        params.put("imei", imei);
        try {
            HttpConnResponse res = requestCommon(params, url);
            if (res.getCode() == 200) {
                String body = res.getBody();
                JSONObject resultJson = new JSONObject(body);
                String data = resultJson.getString("data");
                String decrypt = AESEncryption.decrypt(data);
                Log.e("TAG", "querySkipHomeworkById: " + decrypt);
                System.out.println("res jsonObject = " + decrypt);
                return getResultDTO(new JSONObject(decrypt));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static HttpConnResponse requestCommon(Map<String, Object> params, String url) throws Exception {
        Map<String, String> headers = getHeaders();
        String sign = getSign(params, headers);
        params.put("sign", sign);
        JSONObject homework = new JSONObject(params);
        JSONObject requestJson = new JSONObject();
        System.out.println("paramsJson " + homework.toString());
        requestJson.put("encryptJson", AESEncryption.encrypt(homework.toString()));
        System.out.println("encryptJson " + requestJson);
        HttpConnResponse res = HttpRequestUtil.sendPostRequest(url, requestJson.toString(), headers);
        System.out.println("res code = " + res.getCode());
        System.out.println("res body = " + res.getBody());
        return res;
    }

    private static CardHomeworkResultDTO getResultDTO(JSONObject json) {
        try {
            CardHomeworkResultDTO resultDTO = new CardHomeworkResultDTO();
            if (json.has("homeworkList")) {
                JSONArray homeworkList = json.getJSONArray("homeworkList");
                List<StudentHomeworkDTO> dtoList = new ArrayList<>();
                for (int i = 0; i < homeworkList.length(); i++) {
                    JSONObject objJson = homeworkList.getJSONObject(i);
                    StudentHomeworkDTO dto = new StudentHomeworkDTO();
                    if (objJson.has("homeworkName")) {
                        dto.setHomeworkName(objJson.getString("homeworkName"));
                    }
                    if (objJson.has("sportCount")) {
                        dto.setSportCount(objJson.getInt("sportCount"));
                    }
                    if (objJson.has("sportSeconds")) {
                        dto.setSportSeconds(objJson.getInt("sportSeconds"));
                    }
                    if (objJson.has("type")) {
                        dto.setType(objJson.getInt("type"));
                    }
                    if (objJson.has("status")) {
                        dto.setStatus(objJson.getInt("status"));
                    }
                    if (objJson.has("sportType")) {
                        dto.setSportType(objJson.getInt("sportType"));
                    }
                    if (objJson.has("completedNum")) {
                        dto.setCompletedNum(objJson.getInt("completedNum"));
                    }
                    if (objJson.has("completedTime")) {
                        dto.setCompletedTime(objJson.getInt("completedTime"));
                    }
                    if (objJson.has("homeworkRedirectUrl")) {
                        dto.setHomeworkRedirectUrl(objJson.getString("homeworkRedirectUrl"));
                    }
                    dtoList.add(dto);
                }
                resultDTO.setHomeworkList(dtoList);
            }
            if (json.has("historyRedirectUrl")) {
                resultDTO.setHistoryRedirectUrl(json.getString("historyRedirectUrl"));
            }
            if (json.has("domain")) {
                resultDTO.setDomain(json.getString("domain"));
            }
            if (json.has("expands")) {
                resultDTO.setExpands(json.getJSONArray("expands"));
            }
            return resultDTO;
        } catch (Exception e) {
            return null;
        }
    }

    private static String getSign(Map<String, Object> params, Map<String, String> headers) {
        Map<String, Object> sortMap = new TreeMap<>();
        sortMap.putAll(headers);
        sortMap.putAll(params);
        sortMap.put("key", AESEncryption.ENCRYPTION_KEY);
        sortMap.put("iv", AESEncryption.INIT_VECTOR);
        String sign = sign(sortMap);
        return sign;
    }

    private static Map<String, String> getHeaders() {
        String randomStr = UUID.randomUUID().toString();
        Map<String, String> headers = new TreeMap<>();
        headers.put("appId", APP_ID);
        headers.put("requestTime", String.valueOf(new Date().getTime()));
        headers.put("randomStr", randomStr);
        return headers;
    }

    //生成摘要（入参为TreeMap）
    private static String sign(Map<String, Object> sortMap) {
        StringBuilder sb = new StringBuilder();
        for (Object entry : new TreeMap(sortMap).entrySet()) {
            if (sb.length() > 0) {
                sb.append("!");
            }
            Map.Entry<String, Object> e = (Map.Entry<String, Object>) entry;
            sb.append(e.getKey().toString() + "=" + e.getValue().toString());
        }
        String requestString = sb.toString();
        System.out.println("request paramString = [" + requestString + "] to sign");
        return md5(requestString);
    }

    public static String md5(String input) {
        try {
            // Create MD5 Hash
            MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.update(input.getBytes());
            byte[] messageDigest = digest.digest();
            // Create Hex String
            StringBuilder hexString = new StringBuilder();
            for (byte b : messageDigest) {
                String hex = Integer.toHexString(0xFF & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

}
